/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package globaltradutorws;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author abs
 */
public class HttpRequest {
    public static void httpRequestSite(String link, String pesquisa, String outFile){
        URL url;
        try {
            if (!pesquisa.isEmpty()) {
               //System.out.println(link + URLEncoder.encode(pesquisa,"UTF-8").replace("+",""));            
                url = new URL(link + URLEncoder.encode(pesquisa,"UTF-8").replace("+",""));
               
            }
            else{
               //Criar URL simples
             //  System.out.println(link);
               url = new URL(link);
            }

            URLConnection ligacao = url.openConnection();

            //Ver User-Agent actual de um determinado browser : http://whatsmyuseragent.com
            ligacao.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36");
                 
            BufferedReader in = new BufferedReader(new InputStreamReader(ligacao.getInputStream(),"UTF-8"));
            StringBuilder sb = new StringBuilder();
            String linha;

            while ((linha = in.readLine()) != null) {
                sb.append(linha)
                  .append(System.getProperty("line.separator"));
            }
            
            //Escrever num ficheiro
            BufferedWriter out = new BufferedWriter(new FileWriter(outFile));
            out.write(sb.toString());
           // System.out.println(sb.toString());

            out.close();
            in.close();

        } catch (MalformedURLException ex) {
            //Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            //Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
        } 

    
    }
    
}
